package com.zz.bsea.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.zz.bsea.entity.User;
import com.zz.bsea.web.jdbc.JDBCBasic;
import com.zz.bsea.web.jdbc.Sc;

public class UserService {
	/**
	 * 登录
	 * @param name
	 * @param password
	 * @return
	 */
	public User login(String name,String password){
		System.out.println(name+"***"+password);
		User user=null;
		String sql="select * from tb_user where name=? and password=?";
		Connection conn=JDBCBasic.getConnection();
		try {
			PreparedStatement st=conn.prepareStatement(sql);
			st.setString(1, name);
			st.setString(2, password);
			ResultSet  rs=st.executeQuery();
			while(rs.next()) {
				user =new User();
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				user.setRole(rs.getString("role"));
			}
			
			JDBCBasic.closeConn(st, rs, conn);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return user;
	}
	
	
	public boolean register(String name,String password){
		System.out.println(name+"***"+password);
		boolean flag=false;
		String sql="insert into tb_user(name,password) values (?,?)";
		Connection conn=JDBCBasic.getConnection();
		try {
			PreparedStatement st=conn.prepareStatement(sql);
			st.setString(1, name);
			st.setString(2, password);
			if(st.executeUpdate()>0) {
				flag=true;
			};
			
			
			JDBCBasic.closeConn(st, null, conn);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return flag;
	}
	
	
	public List<User> showAll(){
		List<User> ls=new ArrayList();
		String sql="select * from tb_user";
		Connection conn=JDBCBasic.getConnection();
		try {
			Statement st=conn.createStatement();
			ResultSet  rs=st.executeQuery(sql);
			//如果ResultSet里面没有记录的时候，就返回fase
			//切勿 打印next方法，如果打印就相当于跳过一条记录
			//System.out.println(rs.next());
			while(rs.next()) {
				User user=new User();
				user.setId(rs.getInt("id"));
				user.setName(rs.getString("name"));
				user.setPassword(rs.getString("password"));
				ls.add(user);
			}
			
			JDBCBasic.closeConn(st, rs, conn);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ls;
	}
}
